package com.apes.fn.scm.crossCompany.transfer.service;

import com.apes.fn.scm.crossCompany.transfer.model.CrossCompanyTransfer;
import com.apes.fn.scm.crossCompany.transfer.model.CrossCompanyTransferItem;
import com.apes.fn.scm.crossCompany.transfer.repository.CrossCompanyTransferRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.EventUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.stock.transfer.model.Pick;
import com.apes.scm.stock.transfer.model.PickItem;
import com.apes.scm.stock.transfer.repository.PickRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fn.scm.crossCompany.transfer.service
 * @ClassName: CrossCompanyTransferFlowPick
 * @Author: pyb
 * @CreateTime: 2020-07-01 11:08
 * @Description: 跨公司调拨流转交货单
 * @Version: 1.0
 */
@Service("crossCompanyTransferFlowPickService")
public class CrossCompanyTransferFlowPickService extends DomainService {
    CrossCompanyTransferRepository crossCompanyTransferRepository;

    @Autowired
    private void setCrossCompanyTransferRepository(CrossCompanyTransferRepository crossCompanyTransferRepository) {
        this.crossCompanyTransferRepository = crossCompanyTransferRepository;
    }

    PickRepository pickRepository;

    @Autowired
    private void setPickRepository(PickRepository pickRepository) {
        this.pickRepository = pickRepository;
    }

    /**
     * 创建交货单
     *
     * @param request
     * @return
     */
    private Pick createPickOrder(SimpleRequest request) {
        CrossCompanyTransfer crossCompanyTransfer =crossCompanyTransferRepository.findOne((String) request.get("id"));
        Optional.ofNullable(crossCompanyTransfer).orElseThrow(() -> new RuntimeException("无法找到跨公司调拨单"));
        //创建拣配单
        Pick pick = new Pick();
        Enumeration enumeration = new Enumeration();
        enumeration.setId("one");
        //一次性交货
        pick.setMoveType(enumeration);
        // 公司为发货仓的公司
        pick.setCompany(crossCompanyTransfer.getCompany());
        //合作伙伴为收货仓的公司
        pick.setPartner(crossCompanyTransfer.getReceiptLocation().getCompany());
        pick.setLocation(crossCompanyTransfer.getShipLocation());
        pick.setReceiptLocation(crossCompanyTransfer.getReceiptLocation());
        pick.setOrigin(crossCompanyTransfer.getId());
        pick.setOriginBusinessType(crossCompanyTransfer.getInnerBusinessType());
        // 交货类型： 交货
        pick.setOperation("deliver");
        // 注入场景
        pick.setScene(crossCompanyTransfer.getScene());
        pick.setPickItems(getPickItem(crossCompanyTransfer));
        // 创建交货单
        EventUtil.sendSynEvent(this, "event:stock.pick.save", pick);
        if (crossCompanyTransfer.getState().equals("approve")) {
            crossCompanyTransfer.setState("delivered");
            crossCompanyTransferRepository.saveAndFlush(crossCompanyTransfer);
        }
        return pick;
    }


    /**
     * 功能：获取明细数据
     *
     * @param crossCompanyTransfer
     * @return
     */
    private Set<PickItem> getPickItem(CrossCompanyTransfer crossCompanyTransfer) {
        Set<PickItem> pickItems = crossCompanyTransfer.getCrossCompanyTransferItems().stream().map(
                (CrossCompanyTransferItem item) -> {
                    PickItem pickItem = new PickItem();
                    pickItem.setProduct(item.getProduct());
                    pickItem.setUom(item.getUom());
                    pickItem.setOrderedQty(item.getProductReturnQty());
                    pickItem.setProductUomQty(item.getProductReturnQty());
                    pickItem.setOriginLine(item.getId());
                    return pickItem;
                }).collect(Collectors.toSet());
        return pickItems;
    }

    /**
     * 创建收货单
     *
     * @param request
     * @return
     */
    private Pick createReceiptPick(SimpleRequest request) {
        CrossCompanyTransfer crossCompanyTransfer = request.getO(CrossCompanyTransfer.class);
        Pick deliverPick = pickRepository.findOne(JpaDsl.toCriteriaByEq("origin", crossCompanyTransfer.getId(), "operation", "deliver")).orElseThrow(() -> new RuntimeException("未找到交货单"));
        Enumeration enumeration = new Enumeration();
        enumeration.setId("one");
        Pick pick = new Pick();
        // 交货方式 direct：部分交货，one： 一次性交货
        pick.setMoveType(enumeration);
        // 设置状态
        pick.setState("confirmed");
        // 设置公司
        pick.setCompany(crossCompanyTransfer.getReceiptLocation().getCompany());
        // 设置仓库
        pick.setLocation(crossCompanyTransfer.getReceiptLocation());
        pick.setReceiptLocation(crossCompanyTransfer.getShipLocation());
        // 合作伙伴 发货方的公司
        pick.setPartner(crossCompanyTransfer.getShipLocation().getCompany());
        // 不自动收货
        pick.setAuto(false);
        pick.setOrigin(crossCompanyTransfer.getId());
        pick.setOriginBusinessType(crossCompanyTransfer.getInnerBusinessType());
        // 交货类型：收货
        pick.setOperation("receipt");
        // 注入场景
        pick.setScene(crossCompanyTransfer.getScene());

        // 明细数据，使用交货单的数量作为收货方的收货数量
        Set<PickItem> pickItems = new HashSet<>();
        for (PickItem deliverPickItem : deliverPick.getPickItems()) {
            long result = crossCompanyTransfer.getCrossCompanyTransferItems().stream()
                    .filter(item -> item.getId().equals(deliverPickItem.getOriginLine()))
                    .map(approvalItem -> {
                        double qtyDone = ((Number) deliverPickItem.getQtyDone()).doubleValue();
                        PickItem pickItem = new PickItem();
                        // 获取数量
                        pickItem.setOrderedQty(qtyDone);
                        pickItem.setProduct(approvalItem.getProduct());
                        pickItem.setUom(approvalItem.getUom());
                        pickItem.setProductUomQty(approvalItem.getProductReturnQty());
                        pickItem.setOriginLine(String.valueOf(approvalItem.getId()));

                        pickItems.add(pickItem);
                        return approvalItem;
                    }).count();
            if (result != 1) {
                throw new RuntimeException("跨公司调拨单行号：" + deliverPickItem.getOriginLine() + " 输入错误！");
            }
        }
        pick.setPickItems(pickItems);
        // 创建交货单
        EventUtil.sendSynEvent(this, "event:stock.pick.save", pick);
        return pick;
    }
}
